<template>
  <div>
    <div class="gva-search-box">
      <!-- 搜索框内容 -->
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <!-- <el-button type="primary" icon="plus" @click="openDialog"> 新增 </el-button> -->
      </div>
      <!-- 组件 -->
      <el-table
          :data="tableData"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
      >
        <el-table-column align="left" label="买家名称" min-width="150" prop="buyerName" sortable="custom" />
        <el-table-column align="left" label="卖家名称" min-width="150" prop="sellerName" sortable="custom" />
        <el-table-column align="left" label="交易价格" min-width="150" prop="tradePrice" sortable="custom" />
        <el-table-column align="left" label="完成时间" min-width="200" prop="finishAt" sortable>
          <template #default="scope">
            {{ formatDate(scope.row.finishAt) }}
          </template>
        </el-table-column>
        <el-table-column align="left" label="操作" width="150">
          <template #default="scope">
            <el-button type="text" @click="openDataDrawer(scope.row)">查看数据</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </div>
    <!-- 数据抽屉 -->
    <el-drawer
        v-model="dataDrawerVisible"
        title="数据详情"
        direction="rtl"
        :size="drawerSize"
        @close="resetDataDrawer"
    >
      <el-table :data="dataList">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="ID" prop="id" />
      </el-table>
    </el-drawer>
    <!-- 配置抽屉 -->
    <el-drawer
        v-model="drawerVisible"
        title="新增节点"
        direction="rtl"
        :size="drawerSize"
        @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="服务" prop="ServiceID">
          <el-select
              v-model="form.ServiceID"
              placeholder="请选择服务"
              style="width: 100%"
              @change="change"
          >
            <el-option
                v-for="(optionItem, optionIndex) in serviceData"
                :key="optionIndex"
                :label="optionItem.ServiceName"
                :value="optionItem.ServiceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务配置" prop="ServiceConfig">
          <el-input v-model="form.ServiceConfig" placeholder="请输入服务配置" />
        </el-form-item>
        <el-button @click="drawerVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import {ref, onMounted} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";
import {useRoute} from "vue-router";
import {getListAppDataLog} from "@/api/application";

const route = useRoute();
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const serviceData = ref([]);
const AppId = ref('');
const drawerVisible = ref(false);
const dataDrawerVisible = ref(false); // 新增
const drawerSize = ref("40%");
const formRef = ref(null);
const form = ref({
  ServiceID: "",
  ServiceName: "",
  ServiceConfig: "",
  StartTime: "",
});
const dataList = ref([]); // 新增
const rules = {
  ServiceID: [{required: true, message: "请输入ID", trigger: "blur"}],
  ServiceConfig: [{required: true, message: "请输入服务配置", trigger: "blur"}],
  StartTime: [{required: true, message: "请选择开始时间", trigger: "change"}],
};

const formatStatus = (Status) => {
  switch (Status) {
    case 1:
      return '过期'; // Expired
    case 2:
      return '禁用'; // Disabled
    case 3:
      return '正常'; // Normal
    case 4:
      return '暂停'; // Suspended
    default:
      return '未知'; // Unknown
  }
};

const formatUseType = (UseType) => {
  switch (UseType) {
    case 1:
      return '次数'; // Times
    case 2:
      return '流量'; // Traffic
    case 3:
      return '期限'; // Duration
    default:
      return '未知'; // Unknown
  }
};

const openDataDrawer = (row) => {
  dataList.value = row.dataList || [];
  dataDrawerVisible.value = true;
};

const opendrawerVisible = (row) => {
  form.value = {
    ServiceID: row.ServiceID,
    ServiceName: row.ServiceName,
    ServiceConfig: row.ServiceConfig,
    StartTime: new Date(row.StartTime), // Convert to Date object for date-picker
  };
  drawerVisible.value = true;
};

const change = (value) => {
  const isTrue = serviceData.value.find((list) => list.ServiceId === value);
  if (isTrue) {
    form.value.ServiceName = isTrue.ServiceName;
  } else {
    form.value.ServiceName = "";
  }
  console.log(form.value.ServiceName);
};

const getServiceData = async () => {
  try {
    const response = await getServiceList(-1, -1);
    if (response.code === 0) {
      serviceData.value = response.data.list;
    } else {
      ElMessage.error(response.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取数据失败");
  }
};

const getTableData = async () => {
  try {
    AppId.value = route.query.AppId || '';
    const response = await getListAppDataLog(page.value, pageSize.value, AppId.value);
    if (response.code === 0) {
      tableData.value = response.data.list.map((item) => ({
        ...item,
        finishAt: new Date(item.finishAt), // Convert to Date object for table display
      }));
      total.value = response.data.total;
    } else {
      ElMessage.error(response.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("获取数据失败");
  }
};

onMounted(() => {
  getTableData();
});

const openDialog = () => {
  form.value = {
    ServiceID: "",
    ServiceConfig: "",
    StartTime: new Date(), // Default to current time
  };
  drawerVisible.value = true;
  getServiceData();
};

const resetForm = () => {
  formRef.value.resetFields();
};

const formatDate = (date) => {
  if (date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    const hours = String(d.getHours()).padStart(2, "0");
    const minutes = String(d.getMinutes()).padStart(2, "0");
    const seconds = String(d.getSeconds()).padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  return "";
};

const submitForm = async () => {
  try {
    await formRef.value.validate();
    const response = await addServiceConfig(form.value);
    if (response.code === 0) {
      ElMessage.success("保存成功");
      drawerVisible.value = false;
      getTableData();
    } else {
      ElMessage.error(response.msg || "保存失败");
    }
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("保存失败");
  }
};

const handleCurrentChange = (val) => {
  page.value = val;
  getTableData();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getTableData();
};

const resetDataDrawer = () => {
  dataList.value = [];
};

const handleDelete = async (id) => {
  try {
    await deleteServiceConfig(id);
    ElMessage.success("删除成功");
    getTableData();
  } catch (error) {
    console.error("API Error:", error);
    ElMessage.error("删除失败");
  }
};

const sortChange = (sort) => {
  console.log('Sort Change:', sort);
};

const handleSelectionChange = (val) => {
  console.log('Selection Change:', val);
};
</script>

<style scoped>
.gva-search-box {
  margin-bottom: 20px;
}

.gva-table-box {
  margin-bottom: 20px;
}

.gva-btn-list {
  margin-bottom: 20px;
}

.gva-pagination {
  text-align: right;
  margin-top: 20px;
}
</style>
